package com.atguigu.url.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @version V1.0
 * @author: guangcheng
 * @date: 2021/11/17 15:20
 * @description:
 */
@Component
public class DownloadUtil {
    @Autowired
    MD5DigestUtil md5DigestUtil;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    TaskSplitUtil taskSplit;
    @Autowired
    ThreadPoolExecutor poolExecutor;
    @Autowired
    HttpUtils httpUtils;


    /**
     * 拿到urlSet就开始下载, 不关心获取url的过程
     *
     * @param localDstPath
     * @param urlSet
     */
    public void downloadVideo(String localDstPath, Set<String> urlSet, int piece) {
        //集合有东西就干活
        if (urlSet.size() > 0) {
            System.out.println("url set save to redis and check duplication and download video start");

            urlSet.forEach(url -> {
                String key = md5DigestUtil.getMD5(url);
                //先从redis获取一下, 没有就放
                String str = redisTemplate.opsForValue().get(key);
                if (StringUtils.isEmpty(str)) {

                    String val = key + "_" + "0";
                    redisTemplate.opsForValue().set(key, val);
                }
            });

            ArrayList<String> urlList = new ArrayList<>();
            //去重目标达到了, 转为list
            for (String url : urlSet) {
                urlList.add(url);
            }

            //todo 划分任务
            ArrayList<ArrayList<String>> urlListList = taskSplit.listSplitTo2List(urlList, piece);
            doDownLoadVideoMultiThread(urlListList, localDstPath, piece);
        }
    }


    /**
     * 这个方法可以封装起来, 不让外部调用  改为private即可
     *
     * @param urlListList
     * @param localDstPath
     * @param piece
     */
    public void doDownLoadVideoMultiThread(ArrayList<ArrayList<String>> urlListList, String localDstPath, int piece) {

        //todo 加一些逻辑判断   0 < urlListListSize < 8
        int circle = 1;
        if (urlListList.size() == piece) {
            circle = piece;
        } else {
            circle = urlListList.size();
        }

        for (int i = 0; i < circle; i++) {

            int k = i;
            poolExecutor.submit(() -> {
                for (String url : urlListList.get(k)) {

                    String urlMd5Key = md5DigestUtil.getMD5(url);
                    System.out.println("<< md5摘要: " + urlMd5Key + " ===> " + Thread.currentThread().getName() + " >>");
                    httpUtils.doGetVideo(url, localDstPath);
                }
            });
        }
    }

}

